
'''

边富集的函数整合
KEGG_largest_Net_namelist:最大图名字
GGedgesName:最大图的边名字

stNodesName:斯坦纳树节点名
stEdgesName:斯坦纳树边名


GG:最大联通子图
G:原始图


'''
import pandas as pd
import os
from fishertest_bio import fishertest_bio


def   edge_enrichment(filepath,KEGG_largest_Net_namelist,GGedgesName,stNodesName,stEdgesName,GG,G,writerpath):
    path_result = pd.DataFrame()
    P_value = []
    for i, j, pathlist in os.walk(filepath):
        for p in pathlist:
            pname = filepath + '/' + p
            pathpd = pd.read_excel(pname)
            each_path_name = []  # 每条通路的化合物数(原始网络)
            edge_path = []  # 每条通路的边数(原始网络)

            for c in range(len(pathpd)):
                each_path_name.append(pathpd.loc[c, 'substrate'])
                each_path_name.append(pathpd.loc[c, 'product'])

                pairs = [pathpd.loc[c, 'substrate'], pathpd.loc[c, 'product']]
                edge_path.append(pairs)

            edge_path = [tuple(sorted(i)) for i in edge_path]  # 上三角
            edge_path = list(set(edge_path))

            each_path_name_inLargest = list(
                set([n for n in each_path_name if n in KEGG_largest_Net_namelist]))  # 每条通路的化合物数(最大图)

            # 代谢物富集(最大图)
            hit = [i for i in stNodesName if i in each_path_name_inLargest]
            if each_path_name_inLargest != []:
                cpd_percentage1 = round((len(hit)) / len(each_path_name_inLargest), 4)
            else:
                cpd_percentage1 = 0
            # 边富集

            p, a, b, c, d = fishertest_bio(edge_path, stEdgesName, GGedgesName)

            print('**********************************************************')
            print('通路:', pname)
            print('通路化合物(最大图):', each_path_name_inLargest)
            print('hit:', hit)
            print('**********************************************************')

            path_result = path_result.append(pd.DataFrame(
                {'PathwayName': [pathpd.loc[0, 'pathwayName']],

                 '原网络边数': [len(G.edges())], '原网络节点数': [len(G.nodes())],

                 '最大图边数M': [len(GG.edges())], '最大图节点数': [len(GG.nodes())],

                 '通路边数(原网络)': [len(edge_path)], '通路化合物数(原网络)': [len(each_path_name)],

                 '通路边数(最大图)': [a], '通路化合物数(最大图)': [len(each_path_name_inLargest)],

                 '斯坦纳网边数N': [len(stEdgesName)], '斯坦纳网节点数': [len(stNodesName)],

                 '化合物比例(基于最大图)': [cpd_percentage1], '通路化合物数(斯坦纳网)': [len(hit) if hit != [] else 0],

                 'edge_pvalue(最大图)': [p],

                 '通路边数(最大图)A': [a], 'M-A': [c],
                 '通路边数(斯坦纳网)B': [b], 'N-B': [d],

                 }), ignore_index=True)

    #
    writer = pd.ExcelWriter(writerpath)  # 写入Excel文件
    path_result.to_excel(writer, '')  # ‘page_1’是写入excel的sheet名
    writer.save()

    writer.close()



    return